package com.miniapp.handler;

import com.miniapp.entity.R;
import com.miniapp.handler.exception.BusinessException;
import com.miniapp.handler.exception.PermissionDeniedException;
import com.miniapp.handler.exception.SqlInjectionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.sql.SQLException;

/**
 * @author author
 * @date 2025-09-01 10:23
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理SQL注入异常
     */
    @ExceptionHandler(SqlInjectionException.class)
    public R<Void> handleSqlInjectionException(SqlInjectionException e) {
        log.warn("SQL注入风险检测: {}", e.getMessage());
        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public R<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder("参数校验失败: ");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append("=").append(fieldError.getDefaultMessage()).append(";");
        }
        log.error(errorMsg.toString());
        return R.error(R.ERROR_CODE_PARAM_VALID, errorMsg.toString());
    }

    /**
     * 处理数据库异常
     */
    @ExceptionHandler(SQLException.class)
    public R<Void> handleSQLException(SQLException e) {
        log.error("数据库异常: ", e);
        return R.error(R.ERROR_CODE_DB, "数据库操作失败，请联系管理员");
    }

    /**
     * 处理404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public R<Void> handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("资源不存在: {}", e.getMessage());
        return R.error(404, "请求的资源不存在");
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e) {
        log.error("系统异常: ", e);
        return R.error(R.ERROR_CODE_SYSTEM, "系统异常，请联系管理员");
    }

    @ExceptionHandler(PermissionDeniedException.class)
    public R<Void> handlePermissionDenied(PermissionDeniedException e) {
        log.error("权限: {}", e.getMessage());
        return R.error(e.getMessage());
    }
}
